<template>
  <Dialog v-model="ivrValue" :title="title" width="80%" class="knowledge-form-dialog">
    <div class="form-container">
      <!-- 表单头部 -->
      <div class="form-header">
        <div class="header-icon">
          <Icon icon="ep:document-add" />
        </div>
        <div class="header-content">
          <h3 class="form-title">{{ title }}</h3>
          <p class="form-subtitle">创建新的知识库内容</p>
        </div>
      </div>

      <!-- 表单内容 -->
      <div class="form-content">
        <el-form
          ref="formRef"
          :model="formData"
          label-width="120px"
          :rules="rules"
          class="knowledge-form"
        >
          <div class="form-section">
            <div class="section-title">
              <Icon icon="ep:info-filled" class="section-icon" />
              基础信息
            </div>

            <el-form-item label="标题" prop="title" class="form-item">
              <el-input
                v-model="formData.title"
                placeholder="请输入知识标题"
                class="enhanced-input"
                maxlength="100"
                show-word-limit
              >
                <template #prefix>
                  <Icon icon="ep:edit-pen" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="问题类型" prop="knowledgeType" class="form-item">
              <el-radio-group v-model="formData.knowledgeType" class="type-radio-group">
                <div class="radio-wrapper">
                  <el-radio label="1" class="type-radio">
                    <div class="radio-content">
                      <Icon icon="ep:question-filled" class="radio-icon" />
                      <div class="radio-text">
                        <span class="radio-title">一般问题</span>
                        <span class="radio-desc">常见的通用问题</span>
                      </div>
                    </div>
                  </el-radio>
                </div>

                <div class="radio-wrapper">
                  <el-radio label="2" class="type-radio">
                    <div class="radio-content">
                      <Icon icon="ep:briefcase" class="radio-icon" />
                      <div class="radio-text">
                        <span class="radio-title">业务问题</span>
                        <span class="radio-desc">业务相关的专业问题</span>
                      </div>
                    </div>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="标签名称" class="form-item">
              <el-input
                v-model="formData.labelName"
                placeholder="请输入标签名称（可选）"
                class="enhanced-input"
              >
                <template #prefix>
                  <Icon icon="ep:price-tag" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="关键字" prop="keys" class="form-item">
              <el-input
                v-model="formData.keys"
                type="textarea"
                placeholder="请输入关键字，多个关键字用逗号隔开"
                :rows="3"
                class="enhanced-textarea"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>

          <div class="form-section">
            <div class="section-title">
              <Icon icon="ep:guide" class="section-icon" />
              跳转设置
            </div>

            <el-form-item label="跳转到" prop="jumpType" class="form-item">
              <el-select
                v-model="formData.jumpType"
                placeholder="请选择跳转类型"
                class="enhanced-select"
              >
                <template #prefix>
                  <Icon icon="ep:position" />
                </template>
                <el-option
                  v-for="item in jumpTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <div class="option-content">
                    <Icon :icon="getJumpTypeIcon(item.value)" class="option-icon" />
                    <span>{{ item.label }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="坐席班组"
              v-if="formData.jumpType == 5"
              prop="jumpIndex"
              class="form-item"
            >
              <el-select
                v-model="formData.jumpIndex"
                placeholder="请选择坐席班组"
                class="enhanced-select"
              >
                <template #prefix>
                  <Icon icon="ep:user-filled" />
                </template>
                <el-option
                  v-for="item in agentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.skillId"
                >
                  <div class="option-content">
                    <Icon icon="ep:user" class="option-icon" />
                    <span>{{ item.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="节点"
              v-if="formData.jumpType == 4"
              prop="jumpIndex"
              class="form-item"
            >
              <el-select
                v-model="formData.jumpIndex"
                placeholder="请选择要跳转的节点"
                class="enhanced-select"
              >
                <template #prefix>
                  <Icon icon="ep:connection" />
                </template>
                <el-option
                  v-for="item in ivrOption"
                  :disabled="item.disabled"
                  :key="item.id"
                  :label="item.properties.name"
                  :value="item.id"
                >
                  <div class="option-content">
                    <Icon icon="ep:connection" class="option-icon" />
                    <span>{{ item.properties.name }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="播放次数" class="form-item">
              <el-input-number
                v-model="formData.continuousPlayNum"
                :min="1"
                :max="100"
                class="play-count-input"
              />
              <span class="input-suffix">次</span>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="ivrValue = false" class="cancel-btn">
          <Icon icon="ep:close" class="btn-icon" />
          取消
        </el-button>
        <el-button
          type="primary"
          @click="submit"
          :disabled="formLoading"
          :loading="formLoading"
          class="submit-btn"
        >
          <Icon icon="ep:check" class="btn-icon" />
          {{ formLoading ? '创建中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup>
import { createIvrKnowIssue } from '@/api/call/ivr/index.ts'
import * as LevelApi from '@/api/crm/customerTagConfig'
import { useIvrStore } from '@/store/modules/ivr'
import { skillSimple } from '@/api/call/agent'

defineOptions({ name: 'AddKnowledgeForm' })

const ivrValue = ref(false)
const formLoading = ref(false)
const formRef = ref(null)
const useStore = useIvrStore()

const title = computed(() => {
  return '新增知识内容'
})

const formData = reactive({
  flowId: '',
  groupId: '',
  knowledgeGroupId: '',
  title: '',
  knowledgeType: '',
  labelName: '',
  keys: '',
  jumpType: '',
  jumpIndex: '',
  ignoreSilence: '',
  isSetGrade: '',
  isSendSms: '',
  smsId: '',
  continuousPlayNum: 1,
  type: ''
})

const jumpTypeOptions = [
  { label: '挂机', value: 1 },
  { label: '等待用户应答', value: 2 },
  { label: '下一个主流程', value: 3 },
  { label: '指定节点', value: 4 },
  { label: '转人工', value: 5 },
  { label: '上一个主流程', value: 6 }
]

const levelOptions = ref([])
const agentOptions = ref([])
const ivrOption = ref([])

const rules = reactive({
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  keys: [
    { required: true, message: '关键词不能为空', trigger: 'blur' },
    { min: 1, max: 500, message: '关键词长度不能超过 500 个字符', trigger: 'blur' }
  ],
  knowledgeType: [{ required: true, message: '请选择问题类型', trigger: 'change' }],
  jumpType: [{ required: true, message: '请选择跳转类型', trigger: 'change' }],
  jumpIndex: [{ required: true, message: '请选择跳转目标', trigger: 'change' }]
})

const emit = defineEmits(['success'])

// 获取跳转类型图标
const getJumpTypeIcon = (type) => {
  const iconMap = {
    1: 'ep:phone',
    2: 'ep:timer',
    3: 'ep:right',
    4: 'ep:connection',
    5: 'ep:user',
    6: 'ep:back'
  }
  return iconMap[type] || 'ep:position'
}

const open = async (item) => {
  formData.type = item.type
  formData.groupId = item.groupId
  formData.knowledgeGroupId = item.id
  formData.flowId = item.flowId

  // 重置表单数据
  formData.title = ''
  formData.knowledgeType = ''
  formData.labelName = ''
  formData.keys = ''
  formData.jumpType = ''
  formData.jumpIndex = ''
  formData.continuousPlayNum = 1

  ivrValue.value = true

  // 获取相关数据
  getIvrOption()
  levelOptions.value = await LevelApi.getLevelSimple()
  agentOptions.value = await skillSimple()

  // 重置表单验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const submit = async () => {
  try {
    await formRef.value.validate()
    formLoading.value = true

    await createIvrKnowIssue(formData)
    ElMessage.success('知识内容创建成功')
    ivrValue.value = false
    emit('success')
  } catch (error) {
    console.error('创建知识内容失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error('创建失败，请重试')
    }
  } finally {
    formLoading.value = false
  }
}

const getIvrOption = async () => {
  ivrOption.value = useStore.getLf.getGraphData().nodes
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.knowledge-form-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
    color: white;
    padding: 20px 24px;
  }

  :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
  }

  :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
    font-size: 18px;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    max-height: 70vh;
    overflow-y: auto;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
  }
}

.form-container {
  background: #f8fafc;
}

.form-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background: white;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
}

.header-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.header-content {
  flex: 1;
}

.form-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.form-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.form-content {
  padding: 24px;
}

.knowledge-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
  }

  :deep(.el-form-item__error) {
    font-size: 12px;
  }
}

.form-section {
  margin-bottom: 32px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid rgba(0, 82, 204, 0.1);
}

.section-icon {
  color: #0052cc;
  font-size: 18px;
}

.form-item {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.enhanced-input,
.enhanced-select {
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.enhanced-textarea {
  :deep(.el-textarea__inner) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &:focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.type-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.radio-wrapper {
  width: 168px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;

  &:hover {
    border-color: #0052cc;
    background: rgba(0, 82, 204, 0.02);
  }

  &:has(.el-radio.is-checked) {
    border-color: #0052cc;
    background: rgba(0, 82, 204, 0.05);

    .radio-icon {
      color: #0052cc;
    }

    .radio-title {
      color: #0052cc;
    }
  }
}

.type-radio {
  margin: 0;
  width: 100%;

  :deep(.el-radio__input) {
    position: absolute;
    top: 16px;
    right: 16px;
  }

  :deep(.el-radio__label) {
    padding: 0;
    width: 100%;
  }
}

.radio-content {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.radio-icon {
  font-size: 20px;
  color: #6b7280;
  transition: color 0.2s ease;
}

.radio-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
  flex: 1;
}

.radio-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  transition: color 0.2s ease;
}

.radio-desc {
  font-size: 12px;
  color: #6b7280;
}

.option-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-icon {
  font-size: 14px;
  color: #6b7280;
}

.play-count-input {
  width: 120px;
}

.input-suffix {
  margin-left: 8px;
  color: #6b7280;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: white;
  border-top: 1px solid rgba(0, 82, 204, 0.1);
}

.cancel-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  border-radius: 8px;
  padding: 10px 20px;

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.submit-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;

  &:hover:not(:disabled) {
    background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
  }

  &:disabled {
    background: #9ca3af;
    cursor: not-allowed;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .knowledge-form-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 20px auto;
    }
  }

  .form-header {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .form-content {
    padding: 16px;
  }

  .type-radio-group {
    gap: 8px;
  }

  .radio-wrapper {
    padding: 12px;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .form-container {
    background: #1f2937;
  }

  .form-header {
    background: #374151;
    border-color: rgba(255, 255, 255, 0.1);
  }

  .form-title {
    color: #f9fafb;
  }

  .form-subtitle {
    color: #d1d5db;
  }

  .section-title {
    color: #f9fafb;
  }

  .radio-wrapper {
    background: #4b5563;
    border-color: rgba(255, 255, 255, 0.1);
  }

  .radio-title {
    color: #e5e7eb;
  }

  .radio-desc {
    color: #d1d5db;
  }

  .dialog-footer {
    background: #374151;
    border-color: rgba(255, 255, 255, 0.1);
  }
}
</style>
